package com.tancire.net;

import com.alibaba.fastjson2.JSONObject;
import com.tancire.exceptions.NetErrorException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class NetRequest {

    /**
     * 根据路径请求数据
     *
     * @param url
     * @return
     */
    public static JSONObject request(String url) {
        InputStream cis = null;
        InputStreamReader isReader = null;
        BufferedReader in = null;
        try {
            URL reqUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = reqUrl.openConnection();
            // 设置通用的请求属性
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            cis = connection.getInputStream();
            isReader = new InputStreamReader(cis);
            in = new BufferedReader(isReader);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            return JSONObject.parseObject(sb.toString());
        } catch (Exception e1) {
            throw new NetErrorException("网络请求异常");
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // 输入流关闭失败
                }
            }
            if (null != isReader) {
                try {
                    isReader.close();
                } catch (IOException e) {
                    // Reader关闭失败
                }
            }
            if (null != cis) {
                try {
                    cis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
